<?php

namespace app\adminapi\controller\setting;

use app\adminapi\controller\Base;

class Theme extends Base
{
    /**
     * Get theme config
     */
    public function getConfig()
    {
        try {
            $siteConfig = config('site');
            $template   = $siteConfig['theme']['template'] ?? 'default';

            $data = $template;
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }

        return $this->success('', $data);
    }

    /**
     * Get template list
     */
    public function getTemplateList()
    {
        try {
            $templates = $this->scanTemplates();
            $data      = $templates;
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }

        return $this->success('', $data);
    }

    /**
     * Save theme config
     */
    public function saveConfig()
    {
        try {
            $template = $this->request->post('template', 'default');

            // Check if template exists
            if (!$this->templateExists($template)) {
                return $this->error(trans('template_not_exists'));
            }

            // Read current config
            $configFile = config_path() . '/site.php';
            $config     = require $configFile;

            // Update theme config
            $config['theme']['template'] = $template;

            // Write back to config file
            $content = "<?php\nreturn " . $this->formatArrayAsPhp($config) . ";\n";
            file_put_contents($configFile, $content);

        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * Scan available templates
     */
    private function scanTemplates()
    {
        $templateDir = base_path() . '/app/web/view';
        $templates   = [];

        if (!is_dir($templateDir)) {
            return $templates;
        }

        $dirs = scandir($templateDir);
        foreach ($dirs as $dir) {
            if ($dir === '.' || $dir === '..') {
                continue;
            }

            $templatePath = $templateDir . '/' . $dir;
            if (!is_dir($templatePath)) {
                continue;
            }

            // 检查是否有 template.ini 文件
            $iniFile = $templatePath . '/template.ini';
            if (!file_exists($iniFile)) {
                continue;
            }

            // 解析模板信息
            $templateInfo = $this->parseTemplateIni($iniFile, $dir);
            if ($templateInfo) {
                $templates[] = $templateInfo;
            }
        }

        return $templates;
    }

    /**
     * Parse template config file
     */
    private function parseTemplateIni($iniFile, $templateDir)
    {
        try {
            $ini = parse_ini_file($iniFile, true);

            // Get template info (usually in the first section)
            $templateInfo = null;
            foreach ($ini as $section => $data) {
                if ($section !== 'settings') {
                    $templateInfo          = $data;
                    $templateInfo['value'] = $templateDir;
                    break;
                }
            }

            if (!$templateInfo) {
                return null;
            }

            // Process preview image path
            $preview = $templateInfo['preview'] ?? null;

            $templateInfo['preview'] = $preview && str_starts_with($preview, 'http')
                ? $preview
                : '/static/images/theme-placeholder.jpg';

            return $templateInfo;
        } catch (\Exception $e) {
            return null;
        }
    }

    /**
     * Check if template exists
     */
    private function templateExists($template)
    {
        $templatePath = base_path() . '/app/web/view/' . $template;
        $iniFile      = $templatePath . '/template.ini';

        return is_dir($templatePath) && file_exists($iniFile);
    }

    /**
     * Format array as PHP code
     */
    private function formatArrayAsPhp($array, $indent = 0)
    {
        if (!is_array($array)) {
            return var_export($array, true);
        }

        $spaces     = str_repeat('    ', $indent);
        $nextSpaces = str_repeat('    ', $indent + 1);

        // Check if it is an indexed array
        $isIndexed = array_keys($array) === range(0, count($array) - 1);

        $result = "[\n";

        foreach ($array as $key => $value) {
            $result .= $nextSpaces;

            // If it is not an indexed array, add the key
            if (!$isIndexed) {
                $result .= var_export($key, true) . ' => ';
            }

            // Recursively process the value
            if (is_array($value)) {
                $result .= $this->formatArrayAsPhp($value, $indent + 1);
            } else {
                $result .= var_export($value, true);
            }

            $result .= ",\n";
        }

        $result .= $spaces . ']';

        return $result;
    }
}
